import gnu.io.SerialPort;

import javax.swing.JPanel;

import java.awt.CheckboxMenuItem;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.BorderLayout;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.Serializable;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.util.Calendar;
import java.util.Date;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.JScrollPane;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JComboBox;

public class ConsoleDialog extends JFrame implements ItemListener,KeyListener,propertyReadWritable {

	//private SerialPort obsCommPort = null;
	private static final long serialVersionUID = 1L;
	//private static final String SerializeFileName = new String("OBSComm.dat");  //  @jve:decl-index=0:
	public String frameTitle = new String(" - LScomm");
//	private static final String propertyFile = new String("OBScomm.properties");  //  @jve:decl-index=0:

	private transient JPanel jContentPane = null; 
	private transient JMenu jMenuOption = null;
	private transient JMenuBar jJMenuBarTop = null;
	private transient JMenuItem jMenuItemCOM = null;
	private transient JMenuItem jMenuItemTerminal=null;
	private transient JMenu jMenuConnect = null;
	private transient JCheckBoxMenuItem jCheckBoxMenuItemConnect = null;
	private transient JScrollPane jScrollPane = null;
	protected SerialConsoleTextArea serialConsole = null;
	public Properties config = null;  //  @jve:decl-index=0:
	private Dimension windowSize = new Dimension(400,200);  //  @jve:decl-index=0:
	private Point windowPos = new Point(0,0);
	private JPanel jPanelStatusBar = null;
	private JLabel jLabelStatus = null;
	private JLabel jLabelStatusEast = null;
	private JMenu jMenuView = null;
	private JMenuItem jMenuItemCleareView = null;
	private JMenu jMenuColor = null;
	private JMenuItem jMenuItemColorWhite = null;
	private JMenuItem jMenuItemColorBlack = null;
	private JMenuItem jMenuItemColorGreen = null;
	private JMenuItem jMenuItemFontSet = null;
	private JMenu jMenuHelp = null; //@
	
	
	protected JMenu getJMenuHelp() {
		if (jMenuHelp == null) {
			jMenuHelp = new JMenu("Help"); //@
			jMenuHelp.setMnemonic(KeyEvent.VK_H);
			jMenuHelp.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/icon_info.gif")));

		//	jMenuHelp.add(getJMenuItemHelp()); //@
		}
		return jMenuHelp;
	}

	/**
	 * This method initializes jTextAreaMain	
	 * 	
	 * @return javax.swing.JTextArea	
	 */
	protected SerialConsoleTextArea getJTextAreaMain() {
		if (serialConsole == null) {
			serialConsole = new SerialConsoleTextArea();
			serialConsole.setParent(this);
			//serialConsole.readProperty(config);
		}
		return serialConsole;
	}
	public void onStatusChange(){
		String mode = "";
		if(serialConsole.DispBinaryMode) mode = "(Binary)";
		jLabelStatus.setText(String.format("Rx=%,d%s Tx=%,d ",
				serialConsole.RxCounter,mode,serialConsole.TxCounter));
		
		
	}
	public void setStatusBarEastMessage(String mes){
		jLabelStatusEast.setText(mes);
	}
	/**
	 * This method initializes jMenuOption	
	 * 	
	 * @return javax.swing.JMenu	
	 */
	protected JMenu getJMenuOption() {
		if (jMenuOption == null) {
			jMenuOption = new JMenu("Option");
			jMenuOption.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/cog_edit.png")));
			jMenuOption.setMnemonic(KeyEvent.VK_O);
			jMenuOption.add(getJMenuItemCOM());
			jMenuOption.add(getJMenuItemTerminal());
	//		jMenuOption.add(getJMenuItemTest());
		}
		return jMenuOption;
	}
	/**
	 * This method initializes jJMenuBarTop	
	 * 	
	 * @return javax.swing.JMenuBar	
	 */
	public JMenuBar getJJMenuBarTop() {
		if (jJMenuBarTop == null) {
			jJMenuBarTop = new JMenuBar();
			jJMenuBarTop.add(getJMenuFile());
			jJMenuBarTop.add(getJMenuConnect());
			jJMenuBarTop.add(getJMenuOption());
			//jJMenuBarTop.add(getJMenuHelp());
			jJMenuBarTop.add(getJMenuView());  // Generated
			jJMenuBarTop.add(getJMenuHelp());
		}
		return jJMenuBarTop;
	}
	private JMenu jMenuFile = null;//@
	protected JMenu getJMenuFile() {
		if (jMenuFile == null) {
			jMenuFile = new JMenu("File");
			jMenuFile.setMnemonic(KeyEvent.VK_F);
			jMenuFile.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/folder.png")));

//			jMenuFile.add(getJMenuItemLoad());
//			jMenuFile.add(getJMenuItemSave());
		}
		return jMenuFile;
	}

	/**
	 * This method initializes jMenuItemCOM	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	protected JMenuItem getJMenuItemCOM() {
		if (jMenuItemCOM == null) {
			jMenuItemCOM = new JMenuItem("COM setting");
			jMenuItemCOM.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/cog_edit.png")));

			jMenuItemCOM.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent arg0) {
					getJTextAreaMain().setParamFromDialog();
				}
			});
		}
		return jMenuItemCOM;
	}
	protected JMenuItem getJMenuItemTerminal() {
		if (jMenuItemTerminal == null) {
			jMenuItemTerminal = new JMenuItem("Terminal setting");
			jMenuItemTerminal.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/cog_edit.png")));

			jMenuItemTerminal.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent arg0) {
					getJTextAreaMain().doTerminalSettingDialog();
				}
			});
		}
		return jMenuItemTerminal;
	}

	/**
	 * This method initializes jMenuFile	
	 * 	
	 * @return javax.swing.JMenu	
	 */
	private JMenu getJMenuConnect() {
		if (jMenuConnect == null) {
			jMenuConnect = new JMenu("Connect");
			jMenuConnect.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/disconnect.png")));
			jMenuConnect.setMnemonic(KeyEvent.VK_N);
			jMenuConnect.add(getJCheckBoxMenuItemConnect());
		}
		return jMenuConnect;
	}
	/**
	 * This method initializes jCheckBoxMenuItemConnect	
	 * 	
	 * @return javax.swing.JCheckBoxMenuItem	
	 */
	private JCheckBoxMenuItem getJCheckBoxMenuItemConnect() {
		if (jCheckBoxMenuItemConnect == null) {
			jCheckBoxMenuItemConnect = new JCheckBoxMenuItem("Connect");
			//JMenuItem menuHelpHelp = setupMenuItem("Help-en",KeyEvent.VK_H,"Help(en)");
			jCheckBoxMenuItemConnect.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/disconnect.png")));
			jCheckBoxMenuItemConnect.addItemListener(this);
		}
		return jCheckBoxMenuItemConnect;
	}
	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setViewportView(getJTextAreaMain());
			serialConsole.setAutoscrolls(true);

		}
		return jScrollPane;
	}
//	public static void main(String[] arg){
//		new ConsoleDialog();
//	}
	/**
	 * @param owner
	 */
	public ConsoleDialog() {
	//	super();
		initialize();
		this.setTitle(frameTitle);//@
		this.setJMenuBar(getJJMenuBarTop());//@

		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent e) {
			}
		});
		addKeyListener(this);
		requestFocusInWindow();
		//setVisible(true);//@
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		//this.setSize(new Dimension(227, 90));
		//this.setSize(new Dimension(500, 200));//@
		this.setContentPane(getJContentPane());//@
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.add(getJScrollPane(), BorderLayout.CENTER);
			jContentPane.add(getJPanelStatusBar(), BorderLayout.SOUTH);
		}
		return jContentPane;
	}
	
	private void onExiting(){
	}
	@Override
	public void itemStateChanged(ItemEvent arg0) {
		
		// connect/disconnect
		if(arg0.getSource().equals(jCheckBoxMenuItemConnect)){
			if(!jCheckBoxMenuItemConnect.getState()){ // connecting
				getJTextAreaMain().disconnect();
				setTitle("Disconnected" + frameTitle);
				jCheckBoxMenuItemConnect.setText("Connect");
				jCheckBoxMenuItemConnect.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/disconnect.png")));
				jMenuConnect.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/disconnect.png")));
			}
			else{	 // disconnecting
				try{
					if(getJTextAreaMain().connect()){
						setTitle(getJTextAreaMain().getCommParam()+frameTitle);
						jCheckBoxMenuItemConnect.setText("DisConnect");
						jCheckBoxMenuItemConnect.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/connect.png")));
						jMenuConnect.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/connect.png")));
					}
					else{
						jCheckBoxMenuItemConnect.setState(false);
						JOptionPane.showMessageDialog(this, "Fail to open :\n"+getJTextAreaMain().getCommParam());
					}
				} catch(Exception e){
					e.printStackTrace();
				}
			}
		}
	}
	@Override
	public void keyPressed(KeyEvent arg0) {
	
	}
	@Override
	public void keyReleased(KeyEvent arg0) {
		
	}
	@Override
	public void keyTyped(KeyEvent arg0) {
	}
	@Override
	public void readProperty(Properties prop) {
		config = prop;
		//�@�}���`���j�^���܂߂���ʃT�C�Y�����߂�
		Rectangle virtualBounds = new Rectangle();
	    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
	    GraphicsDevice[] gs = ge.getScreenDevices();
	    for (int j = 0; j < gs.length; j++) {
	        GraphicsDevice gd = gs[j];
	        GraphicsConfiguration[] gc = gd.getConfigurations();
	        for (int i=0; i < gc.length; i++) {
	            virtualBounds = virtualBounds.union(gc[i].getBounds());
	        }
	    }
	    int x,y,h,w;
	    try{
			x = Integer.valueOf(prop.getProperty("CONSOLE-DIALOG/WINDOW_POSX","0"));
			y = Integer.valueOf(prop.getProperty("CONSOLE-DIALOG/WINDOW_POSY","0"));
			w = Integer.valueOf(prop.getProperty("CONSOLE-DIALOG/WINDOW_SIZEX","400"));
			h = Integer.valueOf(prop.getProperty("CONSOLE-DIALOG/WINDOW_SIZEY","200"));
			if(!virtualBounds.contains(x,y) || !virtualBounds.contains(x+w,y+h)){
				x = 0;		y = 0;	w = 400;h = 200;
			}
	    } catch(NumberFormatException e){
			x = 0;	y = 0;	w = 400;h = 200;
	    }
		windowSize.height = h;
		windowSize.width = w;
		windowPos.x = x;
		windowPos.y = y;
		setSize(windowSize.width, windowSize.height);
		setLocation(windowPos);
		serialConsole.readProperty(config);

	}
	@Override
	public void writeProperty(Properties prop) {
		if(prop==null) return;
		Point p = this.getLocationOnScreen();
		prop.put("CONSOLE-DIALOG/WINDOW_POSX", String.valueOf(p.x));
		prop.put("CONSOLE-DIALOG/WINDOW_POSY", String.valueOf(p.y));
		Dimension d = this.getSize();
		prop.put("CONSOLE-DIALOG/WINDOW_SIZEX", String.valueOf(d.width));
		prop.put("CONSOLE-DIALOG/WINDOW_SIZEY", String.valueOf(d.height));
		serialConsole.writeProperty(config);
	}
	
	/**
	 * This method initializes jPanelStatusBar	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	public JPanel getJPanelStatusBar() {
		if (jPanelStatusBar == null) {
			jLabelStatusEast = new JLabel();
			jLabelStatusEast.setText("...");
			jLabelStatusEast.setPreferredSize(new Dimension(200,24));
			jLabelStatus = new JLabel();
			jLabelStatus.setPreferredSize(new Dimension(200,24));
			jLabelStatus.setText("Information");
			jPanelStatusBar = new JPanel();
			jPanelStatusBar.setLayout(new BorderLayout());
			jPanelStatusBar.setMinimumSize(new Dimension(100,24));
			jPanelStatusBar.setPreferredSize(new Dimension(100,24));
			jPanelStatusBar.add(jLabelStatus, BorderLayout.WEST);
			jPanelStatusBar.add(jLabelStatusEast, BorderLayout.EAST);
		}
		return jPanelStatusBar;
	}
	/**
	 * This method initializes jMenuView	
	 * 	
	 * @return javax.swing.JMenu	
	 */
	private JMenu getJMenuView() {
		if (jMenuView == null) {
			jMenuView = new JMenu("View");
			jMenuView.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/monitor.png")));
			jMenuView.setMnemonic(KeyEvent.VK_W);
			jMenuView.add(getJMenuItemCleareView());
			jMenuView.add(getJMenuColor());
			jMenuView.add(getJMenuItemFontSet());
		}
		return jMenuView;
	}
	/**
	 * This method initializes jMenuItemCleareView	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getJMenuItemCleareView() {
		if (jMenuItemCleareView == null) {
			jMenuItemCleareView = new JMenuItem("Clear View");
			jMenuItemCleareView.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/page_white_star.png")));
			jMenuItemCleareView.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent arg0) {
					getJTextAreaMain().resetContents();
				}
			});
		}
		return jMenuItemCleareView;
	}
	/**
	 * This method initializes jMenuColor	
	 * 	
	 * @return javax.swing.JMenu	
	 */
	private JMenu getJMenuColor() {
		if (jMenuColor == null) {
			jMenuColor = new JMenu("Color");
			jMenuColor.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/color.png")));

			jMenuColor.add(getJMenuItemColorWhite());
			jMenuColor.add(getJMenuItemColorBlack());
			jMenuColor.add(getJMenuItemColorGreen());
		}
		return jMenuColor;
	}
	/**
	 * This method initializes jMenuItemColorWhite	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getJMenuItemColorWhite() {
		if (jMenuItemColorWhite == null) {
			jMenuItemColorWhite = new JMenuItem("White");
			jMenuItemColorWhite.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/ConsoleWhite.png")));

			jMenuItemColorWhite.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent arg0) {
					getJTextAreaMain().setColor(0);
				}
			});
		}
		return jMenuItemColorWhite;
	}
	/**
	 * This method initializes jMenuItemColorBlack	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getJMenuItemColorBlack() {
		if (jMenuItemColorBlack == null) {
			jMenuItemColorBlack = new JMenuItem("Black");
			jMenuItemColorBlack.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/ConsoleBlack.png")));
			jMenuItemColorBlack.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent arg0) {
					getJTextAreaMain().setColor(1);
				}
			});
		}
		return jMenuItemColorBlack;
	}
	/**
	 * This method initializes jMenuItemColorGreen	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getJMenuItemColorGreen() {
		if (jMenuItemColorGreen == null) {
			jMenuItemColorGreen = new JMenuItem("Green");
			jMenuItemColorGreen.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/ConsoleBlackGreen.png")));
			jMenuItemColorGreen.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent arg0) {
					getJTextAreaMain().setColor(2);
				}
			});
		}
		return jMenuItemColorGreen;
	}
	/**
	 * This method initializes jMenuItemFontSet	
	 * 	
	 * @return javax.swing.JMenuItem	
	 */
	private JMenuItem getJMenuItemFontSet() {
		if (jMenuItemFontSet == null) {
			jMenuItemFontSet = new JMenuItem("Font");
			jMenuItemFontSet.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/text_uppercase.png")));
			
			jMenuItemFontSet.addActionListener(new ActionListener(){
				@Override
				public void actionPerformed(ActionEvent arg0) {
					getJTextAreaMain().setFontFromDialog();
				}
			});
		}
		return jMenuItemFontSet;
	}
}  //  @jve:decl-index=0:visual-constraint="10,10"
